package com.gcd.gym.common;


import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gcd.gym.utils.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("Authorization");

        // 添加对空 JWT 的检查
        if (jwt == null || jwt.isEmpty()) {
            String message = "未提供认证信息";
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(JsonResult.fail(message)));
            out.flush();
            return false;
        }

        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(jwtSecret)).build();

        try {
            DecodedJWT dj = verifier.verify(jwt);
            return true;
        } catch (JWTVerificationException e) {
            String message = "jwt无效或过期";
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(JsonResult.fail(message)));
            out.flush();
            return false;
        }
    }

}
